package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.mapper.DeviceMapper;
import com.iretailer.report.model.Device;
import com.iretailer.report.model.DeviceMall;
import com.iretailer.report.model.DeviceType;
import com.iretailer.report.model.PhysicalZoneDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Auther Bennie
 * @Date 2020/6/3 14:00
 * @Description
 */
@Service
public class DevicesService extends ServiceImpl<DeviceMapper, Device> {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private PhysicalZoneDeviceService physicalZoneDeviceService;
    @Autowired
    private UserMallService userMallService;


    public PageResult<DeviceMall> grid(String userId, Integer enabled, String deviceStatus, String deviceTypeName, String mallName, String deviceId, QueryOption queryOption) {
        Page<DeviceMall> page = new Page<>(1, Long.MAX_VALUE);
        QueryWrapper<DeviceMall> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("1", 1);
        if (enabled != null) {
            queryWrapper.eq("enabled", enabled);
        }
        if (deviceStatus != null) {
            queryWrapper.eq("deviceStatus", deviceStatus);
        }
        if (deviceTypeName != null) {
            queryWrapper.eq("deviceTypeName", deviceTypeName);
        }
        if (mallName != null) {
            queryWrapper.like("mallName", mallName);
        }
        if (deviceId != null) {
            queryWrapper.like("deviceId", deviceId);
        }
        queryOption.judge(page, queryWrapper);
        if (userId != null) {
//            List<String> childens = userService.getTreeId(userId);
//            childens.add(userId);
//            List<String> mallIds = userMallService.selectMallIdsByUserIds(childens);
//            if (mallIds.size() == 0) {
//                mallIds.add("1");
//            }
            List<String> mallIds = userMallService.selectUserMallIds(userId);
            queryWrapper.in("mallId", mallIds);
        }
        deviceMapper.selectPageDeviceMall(page, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }


    public List<DeviceMall> selectDeviceMall(Wrapper<DeviceMall> wrapper) {
        return deviceMapper.selectDeviceMall(wrapper);
    }

    @CacheEvict(value = {"selectDevice_deviceId", "selectDevice_SN", "getFaceAlarmDevice"}, allEntries = true)
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean deleteDeviceById(List<Long> ids) {
        List<PhysicalZoneDevice> pzds = physicalZoneDeviceService.list(new QueryWrapper<PhysicalZoneDevice>().lambda().in(PhysicalZoneDevice::getDeviceId, ids));
        if (pzds != null && pzds.size() > 0) {
//            return "设备已经被关联，不能删除"
            return false;
        } else {
            deviceMapper.deleteBatchIds(ids);
            return true;
        }
    }

    @CacheEvict(value = {"selectDevice_deviceId", "selectDevice_SN", "getFaceAlarmDevice"}, allEntries = true)
    public boolean saveOrUpdateCamera(Device device) {
        Long id = device.getId();
        device.setUpdateTime(LocalDateTime.now());
        if (id != null) {
            return deviceMapper.updateById(device) > 0;
        } else {
            return deviceMapper.insert(device) > 0;
        }
    }

    @Cacheable(value = "selectDevice_deviceId", key = "#deviceId")
    public Device selectByDeviceId(String deviceId) {
        return getOne(new QueryWrapper<Device>().lambda().eq(Device::getDeviceId, deviceId));
    }

    @Cacheable(value = "selectDevice_SN", key = "#sn")
    public Device selectDeviceBySN(String sn) {
        return getOne(new QueryWrapper<Device>().lambda().eq(Device::getSerialNumber, sn));
    }

    // 更新device的数据和缓存
    @Caching(put = {
            @CachePut(value = {"selectDevice_deviceId"}, key = "#device.deviceId"),
            @CachePut(value = {"selectDevice_SN"}, key = "#device.serialNumber")
    })
    public Device analysisUpdateDevice(Device device) {
        deviceMapper.updateById(device);
        return device;
    }

    public List<DeviceType> selectDeviceType(Wrapper<?> wrapper) {
        return deviceMapper.selectDeviceType(wrapper);
    }
}
